package handler

import (
	"big-fleet-mgr/chone"
	"big-fleet-mgr/modler"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func BranList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var count int64
	modler.DB.Model(&modler.BranOrder{}).Count(&count)
	/*
		SELECT
		  bran_orders.id AS OrderId,
		  brans.bran_code AS BranCode,
		  brans.bran_name AS BranName,
		  brans.bran_no AS BranNo,
		  brans.bran_time AS BranTime,
		  bran_orders.bran_order_code AS BranOrderCode,
		  bran_orders.bran_order_name AS BranOrderName
		FROM
		  bran_orders
		  LEFT JOIN brans ON brans.id = bran_orders.bid
		  WHERE bran_orders.bid=2

	*/

	var list []modler.BranOrderList
	redis_key := "BranList" + strconv.Itoa(page)
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Table(" bran_orders").
			Select(
				"bran_orders.id AS OrderId",
				"brans.bran_code AS BranCode",
				"brans.bran_name AS BranName",
				"brans.bran_no AS BranNo",
				"brans.bran_time AS BranTime",
				"bran_orders.bran_order_code AS BranOrderCode",
				"bran_orders.bran_order_name AS BranOrderName",
			).
			Joins("LEFT JOIN brans ON bran_orders.bid = brans.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		marshal, _ := json.Marshal(list)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成共",
		"data":  list,
		"count": count,
	})
	return
}
func BranDetail(c *gin.Context) {
	id := c.Query("id")
	var list modler.BranOrderList
	redis_key := "BranDetail" + id
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Table(" bran_orders").
			Select(
				"bran_orders.id AS OrderId",
				"brans.bran_code AS BranCode",
				"brans.bran_name AS BranName",
				"brans.bran_no AS BranNo",
				"brans.bran_time AS BranTime",
				"bran_orders.bran_order_code AS BranOrderCode",
				"bran_orders.bran_order_name AS BranOrderName",
			).
			Joins("LEFT JOIN brans ON brans.id = bran_orders.bid").
			Where("bran_orders.id=?", id).
			Debug().
			Find(&list)
		marshal, _ := json.Marshal(list)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成共",
		"data": list,
	})
	return
}
